using System.Xml;
using MessageGateway;

namespace Splitter
{
    public delegate void OnSplitterEvent(XmlDocument msg, int numSplits);

    public class SplitterComponent : SimpleFilter
    {
        protected string nodePath;

        protected OnSplitterEvent splitterEvent;

        public SplitterComponent(IMessageReceiver input, IMessageSender output, string nodePath)
            : base (input, output)
        {
            this.nodePath = nodePath;
            splitterEvent = new OnSplitterEvent(NullEvent);
        }

        public SplitterComponent(string inputQueue, string outputQueue, string xPathNode, 
            IMessageGatewayFactory factory) :
            this(factory.GetReceiverInstance(inputQueue), factory.GetSenderInstance(outputQueue), xPathNode)
        {
        }

        public void AddEventHandler(OnSplitterEvent handler)
        {
            splitterEvent += handler;
        }

        private void NullEvent(XmlDocument message, int numSplits){}

        protected override void OnMessage(XmlDocument message)
        {
            int n = 0;
            XmlNodeList nodeList = message.SelectNodes(nodePath);
            foreach (XmlNode node in nodeList)
            {
                XmlDocument splitDoc = new XmlDocument();
                splitDoc.AppendChild(splitDoc.ImportNode(node, true));
                output.Send(splitDoc);
                n++;
            }
            splitterEvent(message, n);
        }

    }
}
